package org.jeecg.modules.basic.demo.bed.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.IdGeneratorSnowflake;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.basic.demo.apartment.entity.LwgyApartmentCustom;
import org.jeecg.modules.basic.demo.apartment.entity.LwgyBaseApartment;
import org.jeecg.modules.basic.demo.apartment.mapper.LwgyBaseApartmentMapper;
import org.jeecg.modules.basic.demo.apartment.service.ILwgyBaseApartmentService;
import org.jeecg.modules.basic.demo.bed.entity.*;
import org.jeecg.modules.basic.demo.bed.mapper.LwgyBaseBedMapper;
import org.jeecg.modules.basic.demo.bed.service.ILwgyBaseBedService;
import org.jeecg.modules.basic.demo.school.entity.LwgyBaseSchool;
import org.jeecg.modules.basic.demo.student.entity.LwgyBaseStudent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

import static org.jeecg.modules.basic.demo.apartment.service.impl.LwgyBaseApartmentServiceImpl.getSubInnerCode;

/**
 * @Description: 床位信息
 * @Author: jeecg-boot
 * @Date:   2021-01-20
 * @Version: V1.0
 */
@Service
public class LwgyBaseBedServiceImpl extends ServiceImpl<LwgyBaseBedMapper, LwgyBaseBed> implements ILwgyBaseBedService {

    @Autowired
    private ILwgyBaseBedService lwgyBaseBedService;
    @Autowired
    private IdGeneratorSnowflake snowflake;
    @Resource
    private LwgyBaseApartmentMapper lwgyBaseApartmentMapper;
    @Autowired
    private ILwgyBaseApartmentService lwgyBaseApartmentService;
    @Resource
    private LwgyBaseBedMapper lwgyBaseBedMapper;
    private static List<String> ids;

    @Override
    public IPage<LwgyBaseBed> queryPageListCustom(Page<LwgyBaseBed> page, QueryWrapper<LwgyBaseBed> queryWrapper) {
        queryWrapper.isNotNull("vb.id");
        queryWrapper.orderByAsc("bed_code");
        return page.setRecords(lwgyBaseBedMapper.queryPageListCustom(page,queryWrapper));
    }

    @Override
    public IPage<LwgyBaseBed> queryPageListHotelInfo(Page<LwgyBaseBed> page, QueryWrapper<LwgyBaseBed> queryWrapper) {
        queryWrapper.isNotNull("t1.id");
        queryWrapper.orderByAsc("t1.bed_code");
        return page.setRecords(lwgyBaseBedMapper.queryPageListHotelInfo(page,queryWrapper));
    }

    @Override
    public IPage<LwgyBaseBed> queryPageListAllBed(Page<LwgyBaseBed> page, QueryWrapper<LwgyBaseBed> queryWrapper) {
        queryWrapper.isNotNull("id");
        queryWrapper.orderByAsc("bed_code");
        return page.setRecords(lwgyBaseBedMapper.queryPageListAllBed(page,queryWrapper));
    }

    @Override
    public IPage<LwgyBaseBed> queryPageListCustomScore(Page<LwgyBaseBed> page, String scaleBatches,QueryWrapper<LwgyBaseBed> queryWrapper) {
        queryWrapper.orderByAsc("s.total_score");
        return page.setRecords(lwgyBaseBedMapper.queryPageListCustomScore(page,scaleBatches,queryWrapper));
    }

    @Override
    public IPage<LwgyBedAssignment> queryPageNullBed(Page<LwgyBedAssignment> page, QueryWrapper<LwgyBedAssignment> queryWrapper) {
        queryWrapper.orderByAsc("t1.bed_code");
        return page.setRecords(lwgyBaseBedMapper.queryPageNullBed(page,queryWrapper));
    }

    @Override
    public List<Map<String, String>> listByPid(String pid) {
        List<LwgyBaseApartment> apartmentList;
        String workNo="";
        List<Map<String, String>> list;
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        List<String> role = lwgyBaseBedService.getRoleById(sysUser.getId());
        if (role.contains("fdy")) {//不是管理员，显示辅导员所在班级的学生
            String apartmentType;
            if(pid.equals("0")){
                list = lwgyBaseBedMapper.queryListByPid(pid);
            }else{
                LwgyBaseApartment lwgyBaseApartment = lwgyBaseApartmentMapper.getLevel(pid);
                apartmentType = lwgyBaseApartment.getType();
                System.out.print("apartmentTypem"+apartmentType);
                workNo =  sysUser.getWorkNo();
                list = lwgyBaseBedMapper.queryListByPidAndWork(pid,workNo,apartmentType);
            }


          /*  workNo =  sysUser.getWorkNo();
            list = lwgyBaseBedMapper.queryListByPidAndWork(pid,workNo);*/

        }else{
            list = lwgyBaseBedMapper.queryListByPid(pid);
        }

        return list;
    }


    public static volatile Set<LwgyBaseBed> bedSet = new HashSet<>();
    @Override
    public Map<String,String> getApartmentInfo(Set<LwgyBaseApartment> set, String id, String name, String type, Map<String, String> map, ImportLwgyBeds importLwgyBed) {
        String pid = id;
        if(type.equals("bed")){
            QueryWrapper<LwgyBaseBed> bedQueryWrapper = new QueryWrapper<>();
            bedQueryWrapper.eq("name", name);
            bedQueryWrapper.eq("room_id", id);
            List<LwgyBaseBed> bedList = lwgyBaseBedMapper.selectList(bedQueryWrapper);
            String innerCode = lwgyBaseBedMapper.get_maxInnerCode(pid);//查询最大的innerCode
            String innerCode1 = map.get(pid);
            check(map, pid, innerCode, innerCode1);
            LwgyBaseBed lwgyBaseBed;
            if (oConvertUtils.listIsEmpty(bedList)) {
                lwgyBaseBed = new LwgyBaseBed();
                if (id == "0") {
                    lwgyBaseBed.setRoomId("0");
                } else {
                    lwgyBaseBed.setRoomId(id);
                }
                id = String.valueOf(snowflake.snowflakeId());//获取分布式的id
                lwgyBaseBed.setId(id);
                lwgyBaseBed.setName(name);
                lwgyBaseBed.setBedPrice(importLwgyBed.getBedPrice());
//                List<LwgyBaseBed> collect = bedSet.stream().filter(lwgyBaseBed1 -> lwgyBaseBed1.getId().equals(pid)).collect(Collectors.toList());
                List<LwgyBaseApartment> collect = set.stream().filter(lwgyBaseApartment1 -> lwgyBaseApartment1.getId().equals(pid)).collect(Collectors.toList());
                String innerCode2 = "";
                if(oConvertUtils.listIsNotEmpty(collect)){
                    LwgyBaseApartment lwgyBaseApartment = collect.get(collect.size() - 1);
                    innerCode2 = lwgyBaseApartment.getInnerCode();
                }
                innerCode = getSubInnerCode(innerCode2, map.get(pid));
                lwgyBaseBed.setInnerCode(innerCode);
                lwgyBaseBed.setExistFlag(false);
            }else {
                lwgyBaseBed = bedList.get(0);
                innerCode = lwgyBaseBed.getInnerCode();
                lwgyBaseBed.setExistFlag(true);
                id = lwgyBaseBed.getId();
            }
            map.put(pid,innerCode);//把最后的code放入map
            List<LwgyBaseBed> baseBeds = bedSet.stream().filter(baseBed ->
                    baseBed.getRoomId().equals(pid)).filter(baseBed ->
                    baseBed.getName().equals(name)).collect(Collectors.toList());
            if (oConvertUtils.listIsEmpty(baseBeds)) {
                bedSet.add(lwgyBaseBed);
            } else {
                id = baseBeds.get(0).getId();
            }
           /* map.put("id",id);
            return map;*/
        }else{
            LwgyBaseApartment lwgyBaseApartment;
            QueryWrapper queryWrapper = new QueryWrapper<LwgyBaseApartment>();
            queryWrapper.eq("name", name);
            queryWrapper.eq("pid", id);
            List<LwgyBaseApartment> lwgyBaseApartments = lwgyBaseApartmentMapper.selectList(queryWrapper);
            String innerCode = lwgyBaseApartmentService.get_maxInnerCode(pid);//查询最大的innerCode
            String innerCode1 = map.get(pid);
            check(map, pid, innerCode, innerCode1);
            if (oConvertUtils.listIsEmpty(lwgyBaseApartments)) {
                lwgyBaseApartment = new LwgyBaseApartment();
                if (id == "0") {
                    lwgyBaseApartment.setPid("0");
                } else {
                    lwgyBaseApartment.setPid(id);
                }
                id = String.valueOf(snowflake.snowflakeId());//获取分布式的id
                lwgyBaseApartment.setId(id);
                lwgyBaseApartment.setName(name);
                lwgyBaseApartment.setDelFlag("0");
                lwgyBaseApartment.setHasChild("1");
                lwgyBaseApartment.setType(type);
                if("room".equals(type)){
                    lwgyBaseApartment.setRoomOrientation(importLwgyBed.getRoomOrientation());
                    lwgyBaseApartment.setRoomSex(importLwgyBed.getRoomSex());
                }
                List<LwgyBaseApartment> collect = set.stream().filter(lwgyBaseApartment1 -> lwgyBaseApartment1.getId().equals(pid)).collect(Collectors.toList());
                String innerCode2 = "";
                if(oConvertUtils.listIsNotEmpty(collect)){
                    LwgyBaseApartment lwgyBaseApartment1 = collect.get(collect.size() - 1);
                    innerCode2 = lwgyBaseApartment1.getInnerCode();
                }
                innerCode = getSubInnerCode(innerCode2, map.get(pid));
                lwgyBaseApartment.setInnerCode(innerCode);
                lwgyBaseApartment.setExistFlag(false);
            } else {
                lwgyBaseApartment = lwgyBaseApartments.get(0);
                innerCode = lwgyBaseApartment.getInnerCode();
                lwgyBaseApartment.setExistFlag(true);
                id = lwgyBaseApartment.getId();
            }
            map.put(pid,innerCode);//把最后的code放入map
            List<LwgyBaseApartment> schoolList = set.stream().filter(baseSchool ->
                    baseSchool.getPid().equals(pid)).filter(baseSchool ->
                    baseSchool.getName().equals(name)).collect(Collectors.toList());
            if (schoolList.size() <= 0) {
                set.add(lwgyBaseApartment);
            } else {
                id = schoolList.get(0).getId();
            }
        }
        map.put("id",id);
        return map;
    }



    private void check(Map<String, String> map, String pid, String innerCode, String innerCode1) {
        if (oConvertUtils.isNotEmpty(innerCode) && oConvertUtils.isNotEmpty(innerCode1)) {//数据库和集合中的innerCode都不是空
            if (innerCode.compareTo(innerCode1) > 0) {//数据库中的大于于集合中的
                map.put(pid, innerCode);//将集合中的更换为数据库中的
            } else {
                map.put(pid, innerCode1);
            }
        } else {
            if (oConvertUtils.isNotEmpty(innerCode) && oConvertUtils.isEmpty(innerCode1)) {//数据库不是null，集合中的是nul
                map.put(pid, innerCode);//把数据库中的innerCode放入map
            } else if (oConvertUtils.isEmpty(innerCode) && oConvertUtils.isNotEmpty(innerCode1)) {//数据库中的code为空，集合中的不是null
                map.put(pid, innerCode1);//使用集合中的
            } else {
                map.put(pid, "");
            }
        }
    }
    /**
     * 批量创建床位
     * @param lwgyApartmentCustom
     */
    @Override
    public void create_bed(LwgyApartmentCustom lwgyApartmentCustom) {
        List<LwgyBaseBed> bed_list = new ArrayList<>();
        Integer bedsNum = lwgyApartmentCustom.getBedsNum();
        String innerCode = lwgyBaseApartmentService.createInnerCode2(lwgyApartmentCustom.getPid());
        String maxName = lwgyBaseApartmentService.getMaxBedName(lwgyApartmentCustom.getPid());
        for (int i = 0; i < bedsNum; i++) {
            innerCode = lwgyBaseApartmentService.getInnerCodeByList2(innerCode);
            String name = generateBedName(maxName);
            LwgyBaseBed lwgyBaseBed = new LwgyBaseBed();
            lwgyBaseBed.setRoomId(lwgyApartmentCustom.getPid());
            lwgyBaseBed.setBedCode(innerCode);
            lwgyBaseBed.setName(lwgyBaseApartmentService.generateBedCode(innerCode));
            lwgyBaseBed.setBedPrice(lwgyApartmentCustom.getBedsPrice());
//            int num_layer = Integer.parseInt(innerCode.substring(innerCode.length() - 4));
            lwgyBaseBed.setName(name);
            bed_list.add(lwgyBaseBed);
        }
        saveBatch(bed_list);

    }

    private String generateBedName(String maxName) {
        int name = 0;
        try {
            name = Integer.parseInt(maxName);
        }catch (Exception e){
            return "00";
        }
        name = name+1;
        String s = String.format("%0" + 2 + "d", name);
        return s;
    }

    @Override
    public List<String> getRoleById(String id) {
        return lwgyBaseBedMapper.getRoleById(id);
    }

    @Override
    public IPage<LwgyBaseBed> queryPageFacultyBeds(Page<LwgyBaseBed> page, LwgyBaseSchool lwgyBaseSchool) {
        return lwgyBaseBedMapper.queryPageFacultyBeds(page,lwgyBaseSchool);
    }

    @Override
    public List<LwgyBaseBed> queryBedByScInfoId(Page<LwgyBaseBed>page,LwgyBaseApartment lwgyBaseApartment, String studentSex) {
        LwgyBaseBed lwgyBaseBed = new LwgyBaseBed();
        String type = lwgyBaseApartment.getType();
        String id = lwgyBaseApartment.getId();
        if("campus".equals(type)){
            lwgyBaseBed.setCampusId(id);
        }else if("building".equals(type)){
            lwgyBaseBed.setBuildingId(id);
        }else if("unit".equals(type)){
            lwgyBaseBed.setUnitId(id);
        }else if("layer".equals(type)){
            lwgyBaseBed.setLayerId(id);
        }else if("room".equals(type)){
            lwgyBaseBed.setRoomId(id);
        }
        QueryWrapper<LwgyBaseBed> queryWrapper = QueryGenerator.initQueryWrapper(lwgyBaseBed,null);
        queryWrapper.isNull("student_id").or().eq("student_id","");
        queryWrapper.eq("room_sex",studentSex);
        queryWrapper.orderByAsc("bed_code");
        return lwgyBaseBedMapper.queryPageListCustom(page,queryWrapper);
    }

    @Override
    public List<LwgyBaseBed> getBedIdList(String apartmentId, String apartmentType) {
        return lwgyBaseBedMapper.getBedIdList(apartmentId,apartmentType);
    }

    @Override
    public List<LwgyBaseBed> getBedListByStuId(String[] studentId){
        return lwgyBaseBedMapper.getBedListByStuId(studentId);
    }
    @Override
    public List<LwgyBaseBed> getBedListByStuId2(String[] studentId){
        return lwgyBaseBedMapper.getBedListByStuId2(studentId);
    }


    @Override
    public LwgyBaseStudent getStuInfoByBedId(String bedId) {
        return lwgyBaseBedMapper.getStuInfoByBedId(bedId);
    }

    @Override
    public IPage<LwgyBaseStudent> getStuInfoByRoomId(Page<LwgyBaseStudent> page, String roomId) {
//        queryWrapper.isNotNull("s.id");
        return page.setRecords(lwgyBaseBedMapper.getStuInfoByRoomId(roomId));
    }

    @Override
    public List<ImportLwgyBedsA> outBedXls(LwgyBaseBed lwgyBed) {
        String roomId = lwgyBed.getRoomId();
        QueryWrapper<LwgyBaseApartment> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id","type");
        queryWrapper.eq("id",roomId);
        LwgyBaseApartment lwgyBaseApartment = lwgyBaseApartmentMapper.selectOne(queryWrapper);
        lwgyBaseApartment.setDelFlag(lwgyBed.getDelFlag());
        if(oConvertUtils.isEmpty(lwgyBaseApartment)){
            lwgyBaseApartment = new LwgyBaseApartment();//如果没有查询条件，或者查询结果为空，需要初始化一下
        }
        return lwgyBaseBedMapper.outBedXls(lwgyBaseApartment);
    }
    @Override
    public IPage<LwgyBaseBed> queryHolidayPageListCustom(Page<LwgyBaseBed> page, QueryWrapper<LwgyBaseBed> queryWrapper) {
        queryWrapper.isNotNull("vb.id");
        queryWrapper.orderByAsc("bed_code");
        return page.setRecords(lwgyBaseBedMapper.queryHolidayPageListCustom(page,queryWrapper));
    }
    public List<LwgyBaseBed> getStuBed(){
        return lwgyBaseBedMapper.getStuBed();
    }
    @Override
    public void updateStu(String admin_id, List<String> lists){
        lwgyBaseBedMapper.updateStu(admin_id, lists);
    }

    @Override
    public List<BedAndApart> getAllBeds(QueryWrapper<BedAndApart> queryWrapper) {
        return lwgyBaseBedMapper.getAllBeds(queryWrapper);
    }

    @Override
    public List<LwgyBaseBed> findChangeRoom() {
        return lwgyBaseBedMapper.findChangeRoom();
    }

    @Override
    public List<LwgyBaseSchool> getYear() {
        return lwgyBaseBedMapper.getYear();
    }

    @Override
    public List<LwgyBaseBed> getHotelData(QueryWrapper<LwgyBaseBed> queryWrapper) {
        return lwgyBaseBedMapper.getHotelData(queryWrapper);
    }

    @Override
    public void disableBed(String ids) {
        List<String> strings = Arrays.asList(ids.split(","));
        List<LwgyBaseBed> list = new ArrayList<>();
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        boolean hasStudent = false;
        for (String string : strings) {
            LwgyBaseBed lwgyBaseBed = lwgyBaseBedService.getById(string);
            String studentId = lwgyBaseBed.getStudentId();
            if(studentId == null || studentId.length() == 0){
                lwgyBaseBed.setDelFlag("1");
                lwgyBaseBed.setUpdateTime(new Date());
                lwgyBaseBed.setUpdateBy(sysUser.getUsername());
                list.add(lwgyBaseBed);
                System.out.println(list);
            } else {
                hasStudent = true;
            }
        }
        if (hasStudent) {
            throw new RuntimeException("该床位有学生，请先退宿");
        }
        if (!list.isEmpty()) {
            lwgyBaseBedMapper.updateBatchByBedId(list);
        }
    }

    @Override
    public void activateBed(String ids) {
        List<String> strings = Arrays.asList(ids.split(","));
        List<LwgyBaseBed> list = new ArrayList<>();
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        for (String string : strings) {
            LwgyBaseBed lwgyBaseBed = new LwgyBaseBed();
            lwgyBaseBed.setId(string);
            lwgyBaseBed.setDelFlag("0");
            lwgyBaseBed.setUpdateTime(new Date());
            lwgyBaseBed.setUpdateBy(sysUser.getUsername());
            list.add(lwgyBaseBed);
            System.out.println(list);
        }
        if (!list.isEmpty()) {
            lwgyBaseBedMapper.updateBatchByBedId(list);
        }
    }
}

